package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class FileUtils {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private final static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    private final static String accessKeyId = "LTAI4GBqr1TCHS5yBGRGXKdQ";
    private final static String accessKeySecret = "fTUsGyxTsWi9AkmrozagtaorcWzPXP";
    //bucket名称
    private final static String bucketName = "cz-112";


    public static String upload(InputStream inputStream,String filename){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        String path = generatorPath(filename);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path,inputStream);
        // 上传文件。
        ossClient.putObject(putObjectRequest);
        //关闭input流
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return path;
    }

    public static boolean delete(String path){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //删除oss对象
        ossClient.deleteObject(bucketName,path);
        // 关闭OSSClient。
        ossClient.shutdown();
        return true;
    }

    private static String generatorPath(String filename){
        StringBuffer path = new StringBuffer();
        path.append(UUID.randomUUID().toString())
            .append(filename.substring(filename.lastIndexOf(".")));
        return path.toString();
    }

}
